<template>
  <upload
    action="https://upload.qiniup.com/"
    :data="uploadParams"
    ref="upload"
    :show-upload-list="false"
    :format="['jpg','jpeg','png']"
    :before-upload="handleBeforeUpload"
    :on-success="uploadSuccess"
    :max-size="102400">
    <Button type="primary" icon="ios-cloud-upload-outline" >{{buttonText}}</Button>
  </upload>
</template>

<script>
import Upload from "iview/src/components/upload/upload";

export default {
  components: {Upload},
  name: "poster-upload",
  props: ['posterUrl','rate1','rate2','buttonText'],
  computed: {
    uploadParams: function(){
      return {
        token: 'l_Qy04YaEejPEbHcRoptsW1m2c1kzT9G51cAET95:oOtBlfJwmDR86DX5jfO9K6MzVs8=:eyJzY29wZSI6ImJhamlhb3dlYiIsImRlYWRsaW5lIjoxODY3Mzg4NDE3fQ=='
      }
    }
    // text: function () {
    //   return this.buttonText
    // }
  },
  mounted(){
  },
  methods: {
    handleBeforeUpload(file) {
      return new Promise( (resolve, reject) => {
        let reader = new FileReader();
        reader.onload = e => {
          let data = e.target.result;
          let image = new Image();
          image.src= data;
          image.onload = () => {
            if ( image.width >= image.height * this.rate1 && image.width <= image.height * this.rate2 ) {
              resolve()
            } else {
              reject()
              this.$Notice.error({
                title: `文件上传失败,图片宽高比例应为${this.rate1}-${this.rate2}`,
                dese: `图片宽高比例应为${this.rate1}-${this.rate2}`,
                duration: 3
              })
            }
          }
        }
        reader.readAsDataURL(file)

      })
    },
    // 上传成功
    uploadSuccess(event, file) {
      this.$Notice.success({
        title: '文件上传成功',
        dese: `文件${file.name}上传成功`,
        duration: 3
      })
      this.$emit('update:imgUrl', `http://img.bajiaostar.com/${event.key}`)
    }
  }
}
</script>

<style scoped>

</style>
